package com.china08.yxyapi.api.manage.sch.platform.users.teacher;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsSchoolLesson;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsSchoolLessonItem;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsTopicLesson;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsTopicLessonItem;
import com.china08.yxyapi.entity.db.lessons.YxyLessonsVideo;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyLessonsSchoolLessonItemRepository;
import com.china08.yxyapi.repository.db.YxyLessonsSchoolLessonRepository;
import com.china08.yxyapi.repository.db.YxyLessonsTopicLessonItemRepository;
import com.china08.yxyapi.repository.db.YxyLessonsTopicLessonRepository;
import com.china08.yxyapi.repository.db.YxyLessonsVideoRepository;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = { "v01", "教师课程-课时" })
@CrossOrigin
@RestController
@RequestMapping(value = "/api_yw")
public class YxyLessonsTeaItemController extends YxyApiBaseController {
    @Autowired
    private YxyLessonsTopicLessonItemRepository yxyLessonsTopicLessonItemRepository;
    @Autowired
    private YxyLessonsSchoolLessonItemRepository yxyLessonsSchoolLessonItemRepository;
    @Autowired
    private YxyLessonsTopicLessonRepository yxyLessonsTopicLessonRepository;
    @Autowired
    private YxyLessonsSchoolLessonRepository yxyLessonsSchoolLessonRepository;
    @Autowired
    private YxyLessonsVideoRepository yxyLessonsVideoRepository;
    @Autowired
    private ElasticsearchTemplate et;

    @ApiOperation(value = "教师课程-课时添加")
    @Transactional
    @RequestMapping(value = "/manage/tec/lessons/tea/item/create1.e", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> create(HttpServletRequest request, HttpServletResponse response, @RequestBody PageReqModel reqModel) throws JsonParseException, JsonMappingException, IOException {
        List<RespModel> respModels = new ArrayList<RespModel>();
        String author = getProfile(request, response).getUserNick();
        if (reqModel.clzss == 1) {
            try {
                if (!"".equals(reqModel.lessonId) && !"".equals(reqModel.chapterId)) {
                    YxyLessonsSchoolLessonItem item = new YxyLessonsSchoolLessonItem();
                    RespModel rm = new RespModel();
                    Integer num = yxyLessonsSchoolLessonItemRepository.findMaxOrderNumLessonItemByLessonId(reqModel.chapterId);
                    Integer orderNum = 0;
                    if (num == null) {
                        orderNum = 1;
                    } else {
                        orderNum = num + 1;
                    }
                    item.setLessonId(reqModel.lessonId);
                    item.setChapterId(reqModel.chapterId);
                    item.setIntro(reqModel.intro); // 简介
                    item.setTitle(reqModel.title);
                    item.setOrderNum(orderNum);
                    item.setCreatedBy(author);
                    item.setVideoId(reqModel.videoId);
                    item.setPreview(reqModel.preview); // 默认不可视听
                    item.setStatus(0); // 默认草稿
                    if (!"".equals(reqModel.videoId)) {
                        List<YxyLessonsSchoolLessonItem> itms = yxyLessonsSchoolLessonItemRepository.findYxyItemByLessonIdAndChapterIdAndVideoId(reqModel.lessonId, reqModel.chapterId, reqModel.videoId, 0);
                        if (itms.isEmpty()) {
                            try {
                                yxyLessonsSchoolLessonItemRepository.saveAndFlush(item);
                                YxyLessonsSchoolLesson les = yxyLessonsSchoolLessonRepository.findById(reqModel.lessonId);
                                YxyLessonsVideo video = yxyLessonsVideoRepository.findById(item.getVideoId());
                                les.setCount(les.getCount() + 1);// 增加课时
                                les.setDuration(les.getDuration() + video.getDuration());// 增加时长
                                yxyLessonsSchoolLessonRepository.saveAndFlush(les);
                                rm.setIntro(item.getIntro());
                                rm.setTitle(item.getTitle());
                                rm.setId(item.getId());
                                rm.setVideoId(item.getVideoId());
                                rm.setLessonId(item.getLessonId());
                                respModels.add(rm);
                            } catch (Exception e) {
                                rm.setMessage("fail");
                            }
                            // 分页返回
                            Page<RespModel> respPage = new PageImpl<YxyLessonsTeaItemController.RespModel>(respModels, null, 1);
                            return respPage;
                        } else {
                            rm.setMessage("exist");
                        }
                    }
                    try {
                        yxyLessonsSchoolLessonItemRepository.saveAndFlush(item);
                        YxyLessonsSchoolLesson les = yxyLessonsSchoolLessonRepository.findById(reqModel.lessonId);
                        les.setCount(les.getCount() + 1);
                        yxyLessonsSchoolLessonRepository.saveAndFlush(les);
                    } catch (Exception e) {
                        rm.setMessage("fail");
                    }
                    rm.setIntro(item.getIntro());
                    rm.setTitle(item.getTitle());
                    rm.setId(item.getId());
                    rm.setVideoId(item.getVideoId());
                    rm.setLessonId(item.getLessonId());
                    respModels.add(rm);
                }
            } catch (Exception e) {
                RespModel rm = new RespModel();
                rm.setMessage(e.getMessage());
                respModels.add(rm);
                e.printStackTrace();
            }
        } else {
            try {
                if (!"".equals(reqModel.lessonId) && !"".equals(reqModel.chapterId)) {
                    YxyLessonsTopicLessonItem item = new YxyLessonsTopicLessonItem();
                    RespModel rm = new RespModel();
                    Integer num = yxyLessonsTopicLessonItemRepository.findMaxOrderNumLessonItemByLessonId(reqModel.chapterId);
                    Integer orderNum = 0;
                    if (num == null) {
                        orderNum = 1;
                    } else {
                        orderNum = num + 1;
                    }
                    item.setLessonId(reqModel.lessonId);
                    item.setChapterId(reqModel.chapterId);
                    item.setIntro(reqModel.intro); // 简介
                    item.setTitle(reqModel.title);
                    item.setOrderNum(orderNum);
                    item.setVideoId(reqModel.videoId);
                    item.setPreview(0); // 默认不可视听
                    item.setStatus(2); // 草稿
                    if (!"".equals(reqModel.videoId)) {
                        List<YxyLessonsTopicLessonItem> itms = yxyLessonsTopicLessonItemRepository.findYxyItemByLessonIdAndChapterIdAndVideoId(reqModel.lessonId, reqModel.chapterId, reqModel.videoId, 2);
                        if (itms.isEmpty()) {
                            try {
                                yxyLessonsTopicLessonItemRepository.saveAndFlush(item);
                                YxyLessonsTopicLesson les = yxyLessonsTopicLessonRepository.findById(reqModel.lessonId);
                                YxyLessonsVideo video = yxyLessonsVideoRepository.findById(item.getVideoId());
                                les.setCount(les.getCount() + 1);// 增加课时
                                les.setDuration(les.getDuration() + video.getDuration());// 增加时长
                                yxyLessonsTopicLessonRepository.saveAndFlush(les);
                                rm.setIntro(item.getIntro());
                                rm.setTitle(item.getTitle());
                                rm.setId(item.getId());
                                rm.setVideoId(item.getVideoId());
                                rm.setLessonId(item.getLessonId());
                                respModels.add(rm);
                            } catch (Exception e) {
                                rm.setMessage("fail");
                            }
                            // 分页返回
                            Page<RespModel> respPage = new PageImpl<YxyLessonsTeaItemController.RespModel>(respModels, null, 1);
                            return respPage;
                        } else {
                            rm.setMessage("exist");
                        }
                    }
                    try {
                        yxyLessonsTopicLessonItemRepository.saveAndFlush(item);
                        YxyLessonsTopicLesson les = yxyLessonsTopicLessonRepository.findById(reqModel.lessonId);
                        les.setCount(les.getCount() + 1);// 增加课时
                        yxyLessonsTopicLessonRepository.saveAndFlush(les);
                        rm.setIntro(item.getIntro());
                        rm.setTitle(item.getTitle());
                        rm.setId(item.getId());
                        rm.setVideoId(item.getVideoId());
                        rm.setLessonId(item.getLessonId());
                    } catch (Exception e) {
                        rm.setMessage("fail");
                    }
                    respModels.add(rm);
                }
            } catch (Exception e) {
                RespModel rm = new RespModel();
                rm.setMessage(e.getMessage());
                respModels.add(rm);
                e.printStackTrace();
            }
        }
        // 分页返回
        Page<RespModel> respPage = new PageImpl<YxyLessonsTeaItemController.RespModel>(respModels, null, 1);
        return respPage;
    }

    @ApiOperation(value = "教师课程-课时删除")
    @Transactional
    @RequestMapping(value = "/manage/tec/lessons/tea/item/deleteOrUpdate.e", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Page<RespModel> delete(HttpServletRequest request, HttpServletResponse response, @RequestBody PageReqModel reqModel) throws JsonParseException, JsonMappingException, IOException {
        List<RespModel> respModels = new ArrayList<RespModel>();
        String author = getProfile(request, response).getUserNick();
        if (reqModel.clzss == 1) {
            Page<YxyLessonsSchoolLessonItem> quePage = null;
            try {
                if (!"".equals(reqModel.lessonId) && !"".equals(reqModel.chapterId) && !"".equals(reqModel.itemId)) {
                    YxyLessonsSchoolLessonItem item = yxyLessonsSchoolLessonItemRepository.findOne(reqModel.itemId);
                    YxyLessonsSchoolLesson les = yxyLessonsSchoolLessonRepository.findById(reqModel.lessonId);
                    if (item != null) {
                        if (reqModel.status == -1) {
                            item.setStatus(reqModel.status);// 删除
                            yxyLessonsSchoolLessonItemRepository.delete(item.getId());
                        } else { // 编辑状态
                            item.setPreview(reqModel.preview);
                            item.setLastModifiedBy(author);
                            if (!"".equals(reqModel.title)) {
                                item.setTitle(reqModel.title);
                            }
                            if (!"".equals(reqModel.intro)) {
                                item.setIntro(reqModel.intro);
                            }
                            if (!"".equals(reqModel.videoId)) {
                                YxyLessonsVideo video = yxyLessonsVideoRepository.findById(item.getVideoId());
                                YxyLessonsVideo video2 = yxyLessonsVideoRepository.findById(reqModel.videoId);
                                if (video != null && video2 != null) {
                                    les.setDuration(les.getDuration() - video.getDuration() + video2.getDuration());// 增加时长
                                }
                                item.setVideoId(reqModel.videoId);
                            }
                            yxyLessonsSchoolLessonItemRepository.saveAndFlush(item);
                        }
                        les.setLastModifiedBy(author);
                        if (reqModel.status == -1) {
                            if (les.getCount() >= 1) {
                                les.setCount(les.getCount() - 1);// 减课时
                            } else {
                                les.setCount(0);
                            }
                            if (!"".equals(item.getVideoId())) {
                                YxyLessonsVideo video = yxyLessonsVideoRepository.findById(item.getVideoId());
                                if (video != null) {
                                    if (les.getDuration() >= video.getDuration()) {
                                        les.setDuration(les.getDuration() - video.getDuration());// 增加时长
                                    } else {
                                        les.setDuration(0);
                                    }
                                }
                                item.setVideoId(item.getVideoId());
                            }

                            yxyLessonsSchoolLessonRepository.saveAndFlush(les);
                        } else {// 编辑更新时长
                            yxyLessonsSchoolLessonRepository.saveAndFlush(les);
                        }
                        RespModel rm = new RespModel();
                        rm.setIntro(item.getIntro());
                        rm.setTitle(item.getTitle());
                        rm.setId(item.getId());
                        rm.setChapterId(item.getChapterId());
                        rm.setLessonId(item.getLessonId());
                        rm.setVideoId(item.getVideoId());
                        respModels.add(rm);
                    }

                }
            } catch (Exception e) {
                RespModel rm = new RespModel();
                rm.setMessage(e.getMessage());
                respModels.add(rm);
                e.printStackTrace();
            }
        } else {
            try {
                if (!"".equals(reqModel.lessonId) && !"".equals(reqModel.chapterId) && !"".equals(reqModel.itemId)) {
                    YxyLessonsTopicLessonItem item = yxyLessonsTopicLessonItemRepository.findOne(reqModel.itemId);
                    YxyLessonsTopicLesson les = yxyLessonsTopicLessonRepository.findById(reqModel.lessonId);
                    if (item != null) {
                        if (reqModel.status == -1) {
                            item.setStatus(reqModel.status);// 删除
                            yxyLessonsTopicLessonItemRepository.delete(item.getId());
                        } else { // 编辑状态
                            item.setPreview(reqModel.preview);

                            if (!"".equals(reqModel.title)) {
                                item.setTitle(reqModel.title);
                            }
                            if (!"".equals(reqModel.intro)) {
                                item.setIntro(reqModel.intro);
                            }
                            if (!"".equals(reqModel.videoId)) {
                                YxyLessonsVideo video = yxyLessonsVideoRepository.findById(item.getVideoId());
                                YxyLessonsVideo video2 = yxyLessonsVideoRepository.findById(reqModel.videoId);
                                if (video != null && video2 != null) {
                                    les.setDuration(les.getDuration() - video.getDuration() + video2.getDuration());// 增加时长
                                }
                                item.setVideoId(reqModel.videoId);
                            }
                            yxyLessonsTopicLessonItemRepository.saveAndFlush(item);
                        }
                        if (reqModel.status == -1) {
                            les.setCount(les.getCount() - 1);// 减课时
                            if (!"".equals(item.getVideoId())) {
                                YxyLessonsVideo video = yxyLessonsVideoRepository.findById(item.getVideoId());
                                if (video != null) {
                                    les.setDuration(les.getDuration() - video.getDuration());// 减时长
                                }
                            }
                            yxyLessonsTopicLessonRepository.saveAndFlush(les);
                        } else {// 更新时长
                            yxyLessonsTopicLessonRepository.saveAndFlush(les);
                        }
                        RespModel rm = new RespModel();
                        rm.setIntro(item.getIntro());
                        rm.setTitle(item.getTitle());
                        rm.setId(item.getId());
                        rm.setChapterId(item.getChapterId());
                        rm.setLessonId(item.getLessonId());
                        rm.setVideoId(item.getVideoId());
                        respModels.add(rm);
                    }
                }
            } catch (Exception e) {
                RespModel rm = new RespModel();
                rm.setMessage(e.getMessage());
                respModels.add(rm);
                e.printStackTrace();
            }
        }
        // 分页返回
        Page<RespModel> respPage = new PageImpl<YxyLessonsTeaItemController.RespModel>(respModels, null, 1);
        return respPage;
    }

    // 分页请求
    protected static class PageReqModel extends YxyApiPageReqModel {
        public String chapterId;
        public String lessonId; // 课程id
        public String itemId; // 课时id
        public String catalogId;// 分类id
        public Integer status; // 删除状态
        public Integer preview; //
        public String title;
        public String intro;
        public String videoId;//
        public Integer duration;
        public Integer clzss;// 1校本 2专题
    }

    protected static class RespModel extends YxyApiRespModel {
        private String id;
        private String lessonId;
        private String chapterId;// 目录id
        private String pid;
        private String title;// 章节名称
        private String intro;// 简介
        private String videoId;//
        private Integer orderNum;

        /**
         * @return the id
         */
        public String getId() {
            return id;
        }

        /**
         * @param id
         *            the id to set
         */
        public void setId(String id) {
            this.id = id;
        }

        /**
         * @return the lessonId
         */
        public String getLessonId() {
            return lessonId;
        }

        /**
         * @param lessonId
         *            the lessonId to set
         */
        public void setLessonId(String lessonId) {
            this.lessonId = lessonId;
        }

        /**
         * @return the chapterId
         */
        public String getChapterId() {
            return chapterId;
        }

        /**
         * @param chapterId
         *            the chapterId to set
         */
        public void setChapterId(String chapterId) {
            this.chapterId = chapterId;
        }

        /**
         * @return the pid
         */
        public String getPid() {
            return pid;
        }

        /**
         * @param pid
         *            the pid to set
         */
        public void setPid(String pid) {
            this.pid = pid;
        }

        /**
         * @return the title
         */
        public String getTitle() {
            return title;
        }

        /**
         * @param title
         *            the title to set
         */
        public void setTitle(String title) {
            this.title = title;
        }

        /**
         * @return the intro
         */
        public String getIntro() {
            return intro;
        }

        /**
         * @param intro
         *            the intro to set
         */
        public void setIntro(String intro) {
            this.intro = intro;
        }

        /**
         * @return the videoId
         */
        public String getVideoId() {
            return videoId;
        }

        /**
         * @param videoId
         *            the videoId to set
         */
        public void setVideoId(String videoId) {
            this.videoId = videoId;
        }

        /**
         * @return the orderNum
         */
        public Integer getOrderNum() {
            return orderNum;
        }

        /**
         * @param orderNum
         *            the orderNum to set
         */
        public void setOrderNum(Integer orderNum) {
            this.orderNum = orderNum;
        }

    }
}
